﻿using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;

namespace Soul.IdentityServer.Models
{
    public class OpenIdConnectParameters
    {
        private readonly Dictionary<string, string?> _values = new Dictionary<string, string?>();

        internal OpenIdConnectParameters(IFormCollection form)
        {
            foreach (var item in form)
            {
                Add(item.Key, item.Value.FirstOrDefault());
            }
        }

        internal void Add(string key, string? value)
        {
            _values.Add(key, value);
        }

        public string? this[string key]
        {
            get
            {
                if (_values.TryGetValue(key, out string? value))
                    return value;
                return null;
            }
        }
        public string? ClientId => this[OpenIdConnectParameterNames.ClientId];
        public string? ClientSecret => this[OpenIdConnectParameterNames.ClientSecret];
        public string? GrantType => this[OpenIdConnectParameterNames.GrantType];
        public string? Scope => this[OpenIdConnectParameterNames.Scope];
        public string? Username => this[OpenIdConnectParameterNames.Username];
        public string? Password => this[OpenIdConnectParameterNames.Password];
        public string? Code => this[OpenIdConnectParameterNames.Code];
        public string? ResponseType => this[OpenIdConnectParameterNames.ResponseType];
        public string? ResponseMode => this[OpenIdConnectParameterNames.ResponseMode];
        public string? RefreshToken => this[OpenIdConnectParameterNames.RefreshToken];
        public string? TokenType => this[OpenIdConnectParameterNames.TokenType];
        public string? IdToken => this[OpenIdConnectParameterNames.IdToken];
        public string? IdTokenHint => this[OpenIdConnectParameterNames.IdTokenHint];
        public string? AccessToken => this[OpenIdConnectParameterNames.AccessToken];

        public void Validate(string key)
        {
            if (string.IsNullOrWhiteSpace(this[key]))
            {
                throw new ValidationException(ValidationErrors.InvalidRequest, $"'{key}' is required");
            }
        }
    }
}
